const mongoose = require('mongoose')
const {
	Schema
} = mongoose
const {
	userModel
} = require('../models/user.model')
const articleSchema = mongoose.Schema({
	title: {
		type: String,
		required: true,
	},
	description: {
		type: String,
		required: true,
	},
	body: {
		type: String,
		required: true,
	},
	tagList: {
		type: [String],
		ref: 'Tag',
	},
	author: {
		type: Schema.Types.ObjectId,
		ref: 'User',
	},
	read: {
		type: Number,
		default: 0
	},
	favoritedList: { //收藏该文章的用户id
		type: [String]
	},
}, {
	versionKey: false,
	timestamps: true,
})

//判断是否收藏该文章
articleSchema.methods.assertFavorite = function(userId) {
	if (this.favoritedList.includes(userId)) {
		return 1
	} else {
		return 0
	}
}

//收藏文章
articleSchema.methods.addFavorite = function(userId) {
	if (!this.favoritedList.includes(userId)) {
		this.favoritedList.push(userId)
		this.save();
	}

}
// 取消收藏文章
articleSchema.methods.unFavorite = function(userId) {
	for (let i in this.favoritedList) {
		if (this.favoritedList[i] === userId) {
			this.favoritedList.splice(userId, 1)
			this.save()
		}
	}
}
articleSchema.methods.assertTagList = function(tagId) {
	if (!this.favoritedList.includes(tagId)) {
		this.favoritedList.push(tagId)
		this.save();
	}

}
articleSchema.methods.increaseRead =async function() {
	this.read += 1;
	await this.save();
}

articleSchema.methods.toJSONFor = function(user) {
	return {
		_id:this._id,
		title: this.title,
		description: this.description,
		body: this.body,
		createdAt: this.createdAt,
		updatedAt: this.updatedAt,
		tagList: this.tagList,
		read: this.read,
		favorited: user ? this.assertFavorite(user.id) : 0
	};
};

articleSchema.methods.getAuthorInfo = async function(id) {
	const user = await userModel.findById(id);
	console.log('user--',user)
	return {
		username: user.username,
		id: user._id,
		profile:user.profile
	}
}
const articleModel = mongoose.model('Article', articleSchema);

module.exports = {
	articleModel
}
